# ！ /usr/bin/python3
# -*- coding:utf-8 -*-
# @Author:Peng Cao
# @File: 03img_thresh.py
# @Software: PyCharm
import cv2.cv2 as cv
import matplotlib.pyplot as plt
import numpy as np


#  腐蚀处理
def erode_img():
    img = cv.imread('./data/dige.png')
    cv.imshow('img', img)
    kernel = np.ones((3, 3), np.uint8)
    new_img = cv.erode(img, kernel, iterations=1)
    cv.imshow('new_img', new_img)
    new_img2 = cv.dilate(new_img, kernel, iterations=1)
    cv.imshow('new_img2', new_img2)
    cv.waitKey(0)
    cv.destroyAllWindows()


#  膨胀处理
def dilate_img():
    img = cv.imread('./data/pie.png')
    kernel = np.ones((30, 30), np.uint8)
    new_img1 = cv.dilate(img, kernel, iterations=1)
    new_img2 = cv.dilate(img, kernel, iterations=2)
    new_img3 = cv.dilate(img, kernel, iterations=3)
    res = np.hstack((img, new_img1, new_img2, new_img3))  # 横向合并数据，拼图
    cv.imshow('res', res)
    cv.waitKey(0)
    cv.destroyAllWindows()


# 开运算、闭运算、梯度运算、礼帽运算、黑帽运算
def mp_img():
    img = cv.imread('./data/dige.png')
    kernel = np.ones((5, 5), np.uint8)
    new_img1 = cv.morphologyEx(img, cv.MORPH_OPEN, kernel=kernel)  # 开运算：先腐蚀，再膨胀
    new_img2 = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel=kernel)  # 闭运算：先膨胀，后腐蚀
    new_img3 = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel=kernel)  # 梯度= 膨胀-腐蚀,即挖空处理,求边界
    new_img4 = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel=kernel)  # 礼帽=原始输入-开运算
    new_img5 = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel=kernel)  # 黑帽=原始输入-开运算
    res = np.hstack((img, new_img1, new_img2, new_img3, new_img4, new_img5))
    cv.imshow('res', res)
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == '__main__':
    dilate_img()
    # mp_img()
